set -e

# 查找msopgen的路径，加入到环境变量PATH中
msopgen_path=$(find /usr/local/Ascend/ -name msopgen | grep bin)
parent_dir=$(dirname "$msopgen_path")
export PATH=$parent_dir:$PATH

# 利用msopgen生成可编译文件
OP_NAME="AddCustom" # 大驼峰命名
OP_FILE_PATH="add_custom"
rm -rf ./${OP_FILE_PATH}
/usr/local/Ascend/ascend-toolkit/latest/python/site-packages/bin/msopgen gen -i ${OP_FILE_PATH}.json -c ai_core-Ascend910B3 -lan cpp -out ./${OP_FILE_PATH} -m 0 -op ${OP_NAME}
cp -r ./AddCustom/op_host/ ./${OP_FILE_PATH}
cp -r ./AddCustom/op_kernel/ ./${OP_FILE_PATH}
cp -r ./AddCustom/framework/ ./${OP_FILE_PATH}
cd ${OP_FILE_PATH}

# 判断当前目录下是否存在CMakePresets.json文件
if [ ! -f "CMakePresets.json" ]; then
  echo "ERROR, CMakePresets.json file not exist."
  exit 1
fi

# 禁止生成CRC校验和
sed -i 's/--nomd5/--nomd5 --nocrc/g' ./cmake/makeself.cmake

# 修改cann安装路径
sed -i 's:"/usr/local/Ascend/latest":"/usr/local/Ascend/ascend-toolkit/latest":g' CMakePresets.json
# 修改vendor_name 防止覆盖之前vendor_name为customize的算子;
# vendor_name需要和aclnn中的CMakeLists.txt中的CUST_PKG_PATH值同步，不同步aclnn会调用失败;
# vendor_name字段值不能包含customize；包含会导致多算子部署场景CANN的vendors路径下config.ini文件内容截取错误
sed -i 's:"customize":"add_custom":g' CMakePresets.json
bash build.sh

# 安装编译成功的算子包
bash ./build_out/custom_opp*.run
cd ..
#rm -rf ./${OP_FILE_PATH}
